﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

using ShootSearch.Util;
using ShootSearch.Util.Serializers;
using ShootSearch.Runner.Controls;

namespace ShootSearch.Runner.Configurations
{
    [Serializable]
    public class NewTaskConfig
    {
        public const string NAME = "Tasks.config";
        private static string path = RunnerHelper.ConfigPath + "\\" + NAME;

        [XmlArray]
        [XmlArrayItem("Job")]
        public List<JobEntity> Jobs { get; set; }

        [XmlArray]
        [XmlArrayItem("Group")]
        public List<string> Groups { get; set; }
        
        public NewTaskConfig()
        {
            Jobs = new List<JobEntity>();
            Groups = new List<string>();
        }

        public void LoadDefault()
        {
            Jobs.Clear();
            Jobs.Add(new JobEntity(0, new AssemblyConfig()
            {
                TypeName = "ShootSearch.Spiders.HttpSpider",
                Assembly = "ShootSearch.dll"
            }));

            Jobs.Add(new JobEntity(1, new AssemblyConfig()
            {
                TypeName = "ShootSearch.Parsers.Processor",
                Assembly = "ShootSearch.dll"
            }));

            Groups.Clear();

            Groups.Add("Spiders");
            Groups.Add("Parsers");
            Groups.Add("Indexers");


        }


        public static NewTaskConfig Load()
        {
            NewTaskConfig config = new NewTaskConfig();
            if (!File.Exists(path))
            {
                config.LoadDefault();
                config.Save();
            }
            else
            {
                config = XmlFormatter.FromFile(path, config.GetType()) as NewTaskConfig;
                if (config == null) 
                {
                    config = new NewTaskConfig();
                    config.LoadDefault();
                }
            }
            return config;
        }

        public void Save()
        {
            XmlFormatter.ToXmlFile(this, path);
        }
    }

    [Serializable]
    public class JobEntity
    {
        public int Group { get; set; }
        public AssemblyConfig Assembly {get;set;}

        public JobEntity() { }

        public JobEntity(int group, AssemblyConfig assembly)
        {
            this.Group = group;
            this.Assembly = assembly;
        }
    }
}
